package cn.itcast.crm.service.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.itcast.crm.domain.Customer;
import cn.itcast.crm.repository.CustomerRepository;
import cn.itcast.crm.service.CustomerService;

@Service
@Transactional
public class CustomerServiceImpl implements CustomerService {
	
	@Autowired
	CustomerRepository customerRepository;

	@Override
	public List<Customer> findNoAssociationCustomers() {
		return customerRepository.findByFixedAreaIdIsNull();
	}

	@Override
	public List<Customer> findHasAssociationFixedAreaCustomers(String fixedAreaId) {
		return customerRepository.findByFixedAreaId(fixedAreaId);
	}

	@Override
	public void associationCustomersToFixedArea(String customerIdStr, String fixedAreaId) {
		// 第一步：先删除fixedAreaId对应的值
		customerRepository.clearFixedAreaId(fixedAreaId);
		
		// 第二步：再重新关联fixedAreaId和customerIdStr的值
		// customerIdStr表示将所有客户id 拼成字符串 1,2,3
		if(StringUtils.isBlank(customerIdStr)){
			return;
		}
		String[] customerIds = customerIdStr.split(",");
		for(String customerId:customerIds){
			customerRepository.updateFixedAreaId(fixedAreaId,Integer.parseInt(customerId));
		}
	}

	@Override
	public void regist(Customer customer) {
		customerRepository.save(customer);
	}

	@Override
	public Customer findCustomerByTelephone(String telephone) {
		
		return customerRepository.findByTelephone(telephone);
	}

	@Override
	public void updateType(String telephone) {
		customerRepository.updateType(telephone);
	}

	@Override
	public Customer findCustomerByTelephoneAndPassword(String telephone, String password) {
		return customerRepository.findByTelephoneAndPassword(telephone,password);
	}

	@Override
	public String findFixedAreaIdByAddressAndCustomerId(String address, Integer customerId) {
		return customerRepository.findFixedAreaIdByAddressAndCustomerId(address,customerId);
	}

}
